import os
import re
# import json

import openpyxl
# from openpyxl.utils import get_column_letter, column_index_from_string

'''
    ws.title string 表名 ["通天塔"] = {}
    A1 导出的行范围 3-10, 3-, -10
'''


class Xls2lua:
    def __init__(self, file_path):
        self.__path = file_path
        self.__wb = openpyxl.load_workbook(self.__path, data_only=True)
        self.__ws = self.__wb.active
        # print("init...")

    def __get_rows(self):
        """
        根据xls工作表A2单元格的内容获取范围
        :return: min_row[int], max_row[int]
        """
        row_index = str(self.__ws.cell(1,1).value or "").split("-")
        min_row = int(row_index[0] or 3)
        max_row = int(row_index[1]) if len(row_index) == 2 and row_index[1] else self.__ws.max_row
        return min_row, max_row

    def __str2num(self, data):
        if data.endswith("W") or data.endswith("w"):
            res = float(data.rstrip("W").rstrip("w")) * 10000
        else:
            res = float(data)
        
        if res == int(res):
            return int(res)

        return res

    def __num2str(self, data):
        if data // 10000 > 0:
            res = data / 10000
            return f'{int(res)}W' if res == int(res) else f'{res}W'

        res = int(data) if data == int(data) else data
        return str(res)

    def __get_col_id(self, col_name):
        row = list(self.__ws.values)[1]
        desc_col_id = row.index(col_name)
        return desc_col_id

    def __write_xls(self, lst):
        nwb = openpyxl.Workbook()
        nws = nwb.active
        for v in lst:
            nws.append(v)

        dir_name = os.path.dirname(self.__path)
        path = f'{dir_name}/temp.xlsx'
        nwb.save(path)
        os.system(path)

    def __write_file(self, code, path=None):
        isOpen = path == None
        if not path:
            path = f'{os.path.dirname(self.__path)}/temp.lua'

        with open(path, 'w', encoding='utf-8') as obj:
            obj.write(code)

        if isOpen:
            os.system(path)

    def key2str(self, data, data_type):
        if data_type == 'i':
            return f'\n\t[{data}] = {{'
        return f'\n\t["{data}"] = {{'

    def value2str(self, data, data_type):
        if data_type == 's1':
            return f"'{data}',"
            
        if data_type == 's2':
            return f'[[{data}]],'

        if data_type == 'i':
            return f'{data},'

        if data_type == 'arr':
            res = '", "'.join(data.split(', '))
            return f'{{"{res}"}},'
        
        if data_type == 'annotation':
            res = ""
            for line in data.split('\n'):
                res += f'\n\t\t-- {line}'
            return res

    def desc2str(self, data, is_line_by_line=None):
        if not is_line_by_line:
            values = ""
            i = 0
            while True:
                pattern = "(\-?\d+(\.\d+)?[Ww]?)"
                match = re.search(pattern, data)
                if not match:
                    break
                i += 1
                data = data.replace(match.group(1), f'<{chr(i+64)}>', 1)
                values += f'{chr(i+64)} = {self.__str2num(match.group(1))}, '
            data = re.sub("\n|,|，", "|n", data)
            # print(data)
            return f'\n\t\tdesc = [[{data}]],\n\t\t{values}'

        res = "\n\t\tdata = {"
        get_vavlue = '\n\t\t\t\tget_value = function(params)'
        get_vavlue += '\n\t\t\t\t\treturn params.data.A * params.lv'
        get_vavlue += '\n\t\t\t\tend,'
        desc_list = data.split("\n")
        for v in desc_list:
            desc = "\n\t\t\t{\n\t\t\t\tdesc = "
            values = ""
            i = 0
            while True:
                pattern = "(\-?\d+(\.\d+)?[Ww]?)"
                match = re.search(pattern, v)
                if not match:
                    break
                i += 1
                idx = chr(i+64)
                v = v.replace(match.group(1), f'<{idx}>', 1)
                values += f'{chr(i+64)} = {self.__str2num(match.group(1))}, '
            desc += f'"{v}<CUR>"' + ",\n\t\t\t\t" + values + get_vavlue + '\n\t\t\t},'
            res += desc
        res += "\n\t\t},"
        return res

    def write_lua_cfg(self):
        code = f'gtable["{self.__ws.title}"] = {{'
        types = list(self.__ws.values)[0]
        keys = list(self.__ws.values)[1]
        min_row, max_row = self.__get_rows()
        rows = list(self.__ws.values)[min_row-1:max_row]
        try:
            is_line_by_line = [c.value for c in list(self.__ws.columns)[self.__get_col_id('line_by_line')]][2:]
        except:
            is_line_by_line = []
        values_in_one_line = self.__ws.cell(2, 1).value
        j = 0
        for row in rows:
            key = False
            for i, v in enumerate(row):
                if not types[i] or not v:
                    # 此列/单元格内容不需要导出
                    continue
                
                if not key:
                    # 第一列作为key
                    key = True
                    code += self.key2str(v, types[i])

                if types[i] == 'desc':
                    code += self.desc2str(v, is_line_by_line[j])
                    # code += self.desc2str(v)
                    continue
                
                if types[i] == 'annotation':
                    code += self.value2str(v, types[i])
                    continue
                
                if values_in_one_line:
                    prefix = ' '
                else:
                    prefix = '\n\t\t'
                code += prefix + f'{keys[i]} = {self.value2str(v, types[i])}'                  

            if values_in_one_line:
                prefix = ' '
            else:
                prefix = '\n\t'
            code += prefix + '},'
            j += 1
        code += '\n}'

        # print(code)
        self.__write_file(code)

    def __get_buff_tpl_script(self):
        tpl_path = './python\\bonus_tpl.lua'
        with open(tpl_path, 'r', encoding='utf-8') as obj:
            code = obj.read()
        return code

    def write_buff_tpl(self):
        """批量写Buff模版文件

        Args:
            module (str): 模块名称
            cfg_name (str): 配置表名称
        """
        module = self.__ws.title
        # cfg_name = self.__ws.cell(1,1).value
        min_row, max_row = self.__get_rows()
        col_id = self.__get_col_id("name")
        # desc_col_id = self.__get_col_id("fmt_desc")
        # id_col_id = self.__get_col_id("id")
        name_lst = [c.value for c in list(self.__ws.columns)[col_id]][min_row-1:max_row]
        # desc_lst = [c.value for c in list(self.__ws.columns)[desc_col_id]][min_row-1:max_row]
        # id_lst = [c.value for c in list(self.__ws.columns)[id_col_id]][min_row-1:max_row]

        tpl = self.__get_buff_tpl_script()
        for i, name in enumerate(name_lst):
            # name = f'羁绊{name}'
            code = tpl
            code = code.replace('<name>', name)
            code = code.replace('<module>', module)
            # code = code.replace('<cfg_name>', cfg_name)
            # code = code.replace('<id>', str(id_lst[i]))

            # 写入mod_attr()
            # desc = desc_lst[i]
            # code = code.replace('-- <mod_attr>', self.__get_mod_attr_script(desc))

            path = f'{self.__ws.cell(2, 1).value}/{name}.lua' if self.__ws.cell(2, 1).value else None
            self.__write_file(code, path)
        print(f'总计{len(name_lst)}个文件已生成完毕')


if __name__ == "__main__":
    file_path = input("工作簿路径：") or r"e:\桌面\所谓仙途.xlsx"
    xls2lua = Xls2lua(file_path)
    # xls2lua.write_lua_cfg()
    xls2lua.write_buff_tpl()
